package com.dongao.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDownloadUtil {
	
	/**
	 * 下载文件
	 * @param url
	 * @param path
	 * @param fileName
	 * @return
	 */
	public static int downloadFile(String url, String path, String fileName) {
		InputStream inputStream = null;
		
		if (FileUtil.isFileExist(fileName, path)) {
			return 1;
		} else {
			try {
				inputStream = getInputStreamFromUrl(url);
				File resultFile = FileUtil.write2SDFromInput(path, fileName, inputStream);
				if (resultFile == null) {
					return -1;
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return 0;
		
	}
	
	/**
	 * 从给定url中获得输入流
	 * @param urlStr
	 * @return inputStream
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public static InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		InputStream inputStream = conn.getInputStream();
		return inputStream;
	}
	
}
